"use client"

import { useEffect, useState } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Loader2, RefreshCw, AlertCircle, Plus, Upload, Download, Users, Star, Tag } from 'lucide-react';
import { get, post, put, del } from '@/lib/apiClient';
import { ContactsDataTable } from '@/components/contacts/ContactsDataTable';
import { ContactForm } from '@/components/contacts/ContactForm';
import { ImportDialog } from '@/components/contacts/ImportDialog';
import { ExportDialog } from '@/components/contacts/ExportDialog';
import type { Contact } from '@/components/contacts/columns';

interface ContactsResponse {
  success: boolean;
  contacts: Contact[];
  pagination: {
    page: number;
    per_page: number;
    total: number;
    pages: number;
    has_next: boolean;
    has_prev: boolean;
  };
}

interface GroupsResponse {
  success: boolean;
  groups: string[];
  stats: Record<string, number>;
}

interface TagsResponse {
  success: boolean;
  tags: string[];
  stats: Record<string, number>;
}

interface ExportResponse {
  success: boolean;
  data: string | unknown[];
  format: string;
  count: number;
}

export default function Contacts() {
  const [contacts, setContacts] = useState<Contact[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [stats, setStats] = useState({
    total: 0,
    groups: 0,
    favorites: 0,
    tags: 0
  });

  // 表单和对话框状态
  const [formOpen, setFormOpen] = useState(false);
  const [editingContact, setEditingContact] = useState<Contact | null>(null);
  const [importOpen, setImportOpen] = useState(false);
  const [exportOpen, setExportOpen] = useState(false);

  // 筛选状态
  const [currentGroupFilter, setCurrentGroupFilter] = useState<string | null>(null);
  const [currentTagFilter, setCurrentTagFilter] = useState<string | null>(null);
  const [currentFavoriteFilter, setCurrentFavoriteFilter] = useState<boolean | null>(null);

  // 分组和标签数据
  const [groups, setGroups] = useState<string[]>([]);
  const [tags, setTags] = useState<string[]>([]);

  // 加载联系人数据
  const loadContacts = async () => {
    try {
      setLoading(true);
      setError(null);

      const params = new URLSearchParams();
      if (currentGroupFilter) params.append('group', currentGroupFilter);
      if (currentTagFilter) params.append('tags', currentTagFilter);
      if (currentFavoriteFilter !== null) params.append('is_favorite', currentFavoriteFilter.toString());

      const response = await get<ContactsResponse>(`/contacts?${params.toString()}`);
      
      if (response.success) {
        setContacts(response.contacts);
        setStats(prev => ({
          ...prev,
          total: response.pagination.total,
          favorites: response.contacts.filter(c => c.is_favorite).length
        }));
      }
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : '加载联系人失败');
      console.error('Failed to load contacts:', err);
    } finally {
      setLoading(false);
    }
  };

  // 加载分组和标签数据
  const loadGroupsAndTags = async () => {
    try {
      const [groupsResponse, tagsResponse] = await Promise.all([
        get<GroupsResponse>('/contacts/groups'),
        get<TagsResponse>('/contacts/tags')
      ]);

      if (groupsResponse.success) {
        setGroups(groupsResponse.groups);
        setStats(prev => ({ ...prev, groups: groupsResponse.groups.length }));
      }

      if (tagsResponse.success) {
        setTags(tagsResponse.tags);
        setStats(prev => ({ ...prev, tags: tagsResponse.tags.length }));
      }
    } catch (err) {
      console.error('Failed to load groups and tags:', err);
    }
  };

  useEffect(() => {
    loadContacts();
  }, [currentGroupFilter, currentTagFilter, currentFavoriteFilter]);

  useEffect(() => {
    loadGroupsAndTags();
  }, []);

  // 处理新建联系人
  const handleCreate = () => {
    setEditingContact(null);
    setFormOpen(true);
  };

  // 处理编辑联系人
  const handleEdit = (contact: Contact) => {
    setEditingContact(contact);
    setFormOpen(true);
  };

  // 处理保存联系人
  const handleSave = async (contactData: Omit<Contact, 'id' | 'created_at' | 'updated_at'>) => {
    try {
      if (editingContact) {
        // 更新联系人
        await put(`/contacts/${editingContact.id}`, contactData);
      } else {
        // 创建联系人
        await post('/contacts', contactData);
      }
      
      await loadContacts();
      await loadGroupsAndTags();
    } catch (err: unknown) {
      throw new Error(err instanceof Error ? err.message : '保存失败');
    }
  };

  // 处理删除联系人
  const handleDelete = async (contact: Contact) => {
    if (!confirm(`确定要删除联系人"${contact.name}"吗？`)) return;

    try {
      await del(`/contacts/${contact.id}`);
      await loadContacts();
      await loadGroupsAndTags();
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : '删除失败');
    }
  };

  // 处理切换收藏状态
  const handleToggleFavorite = async (contact: Contact) => {
    try {
      await put(`/contacts/${contact.id}/favorite`);
      await loadContacts();
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : '操作失败');
    }
  };

  // 处理批量删除
  const handleBatchDelete = async (contacts: Contact[]) => {
    try {
      await post('/contacts/batch-delete', { ids: contacts.map(c => c.id) });
      await loadContacts();
      await loadGroupsAndTags();
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : '批量删除失败');
    }
  };

  // 处理批量切换收藏状态
  const handleBatchToggleFavorite = async (contacts: Contact[], isFavorite: boolean) => {
    try {
      const promises = contacts.map(contact => 
        put(`/contacts/${contact.id}`, { is_favorite: isFavorite })
      );
      await Promise.all(promises);
      await loadContacts();
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : '批量操作失败');
    }
  };

  // 处理导入
  const handleImport = async (data: Record<string, unknown>[]) => {
    try {
      await post('/contacts/import', { contacts: data });
      await loadContacts();
      await loadGroupsAndTags();
    } catch (err: unknown) {
      throw new Error(err instanceof Error ? err.message : '导入失败');
    }
  };

  // 处理导出
  const handleExport = async (format: string, contactIds?: number[]) => {
    try {
      const response = await post<ExportResponse>('/contacts/export', { 
        format, 
        ids: contactIds 
      });
      
      if (response.success) {
        const data = response.data;
        const filename = `contacts_${new Date().toISOString().split('T')[0]}.${format}`;
        
        if (format === 'json') {
          const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = filename;
          a.click();
          URL.revokeObjectURL(url);
        } else if (format === 'csv' && typeof data === 'string') {
          const blob = new Blob([data], { type: 'text/csv' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = filename;
          a.click();
          URL.revokeObjectURL(url);
        }
      }
    } catch (err: unknown) {
      throw new Error(err instanceof Error ? err.message : '导出失败');
    }
  };

  // 处理导出选中联系人
  const handleExportSelected = (contacts: Contact[]) => {
    // 这里可以打开导出对话框，或者直接导出
    handleExport('csv', contacts.map(c => c.id));
  };

  if (loading && contacts.length === 0) {
    return (
      <div className="flex items-center justify-center h-96">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center h-96 gap-4">
        <AlertCircle className="h-12 w-12 text-destructive" />
        <p className="text-destructive">{error}</p>
        <Button onClick={loadContacts}>重试</Button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">通讯录</h1>
          <p className="text-muted-foreground mt-2">管理您的联系人信息</p>
        </div>
        
        <div className="flex gap-2">
          <Button onClick={loadContacts} variant="outline" size="sm">
            <RefreshCw className="h-4 w-4 mr-2" />
            刷新
          </Button>
          <Button onClick={() => setImportOpen(true)} variant="outline" size="sm">
            <Upload className="h-4 w-4 mr-2" />
            导入
          </Button>
          <Button onClick={() => setExportOpen(true)} variant="outline" size="sm">
            <Download className="h-4 w-4 mr-2" />
            导出
          </Button>
          <Button onClick={handleCreate} size="sm">
            <Plus className="h-4 w-4 mr-2" />
            新建联系人
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">总联系人</p>
              <p className="text-2xl font-bold">{stats.total}</p>
            </div>
            <Users className="h-8 w-8 text-primary" />
          </div>
        </Card>
        
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">分组数量</p>
              <p className="text-2xl font-bold">{stats.groups}</p>
            </div>
            <Badge className="h-8 w-8 rounded-full flex items-center justify-center">
              <span className="text-sm font-bold">{stats.groups}</span>
            </Badge>
          </div>
        </Card>
        
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">收藏联系人</p>
              <p className="text-2xl font-bold">{stats.favorites}</p>
            </div>
            <Star className="h-8 w-8 text-yellow-500" />
          </div>
        </Card>
        
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">标签数量</p>
              <p className="text-2xl font-bold">{stats.tags}</p>
            </div>
            <Tag className="h-8 w-8 text-blue-500" />
          </div>
        </Card>
      </div>

      {/* 数据表格 */}
      <Card className="p-6">
        <ContactsDataTable
          data={contacts}
          loading={loading}
          onEdit={handleEdit}
          onDelete={handleDelete}
          onToggleFavorite={handleToggleFavorite}
          onBatchDelete={handleBatchDelete}
          onBatchToggleFavorite={handleBatchToggleFavorite}
          onExport={handleExportSelected}
          groups={groups}
          tags={tags}
          onGroupFilter={setCurrentGroupFilter}
          onTagFilter={setCurrentTagFilter}
          onFavoriteFilter={setCurrentFavoriteFilter}
          currentGroupFilter={currentGroupFilter}
          currentTagFilter={currentTagFilter}
          currentFavoriteFilter={currentFavoriteFilter}
        />
      </Card>

      {/* 联系人表单对话框 */}
      <ContactForm
        open={formOpen}
        onOpenChange={setFormOpen}
        contact={editingContact}
        onSave={handleSave}
        groups={groups}
        tags={tags}
      />

      {/* 导入对话框 */}
      <ImportDialog
        open={importOpen}
        onOpenChange={setImportOpen}
        onImport={handleImport}
      />

      {/* 导出对话框 */}
      <ExportDialog
        open={exportOpen}
        onOpenChange={setExportOpen}
        contacts={contacts}
        selectedContacts={[]} // 这里可以根据需要传入选中的联系人
        onExport={handleExport}
      />
    </div>
  );
}
